package com.example.ivideo_2211a.fyt

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.ivideo_2211a.R
import com.example.ivideo_2211a.databinding.ItemCategoryBinding
import com.example.ivideo_2211a.model.FtyTopeEntity

class FtyTypeAdapter(
    private val onTypeClick: (FtyTopeEntity) -> Unit
) : ListAdapter<FtyTopeEntity, FtyTypeAdapter.TypeViewHolder>(TypeDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TypeViewHolder {
        val binding = ItemCategoryBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return TypeViewHolder(binding)
    }

    override fun onBindViewHolder(holder: TypeViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class TypeViewHolder(
        private val binding: ItemCategoryBinding
    ) : RecyclerView.ViewHolder(binding.root) {
        fun bind(type: FtyTopeEntity) {
            binding.categoryText.text = type.name
            if (type.isSelected) {
                binding.categoryText.setTextColor(
                    ContextCompat.getColor(binding.root.context, R.color.primary_color)
                )
                binding.categoryIcon.setColorFilter(
                    ContextCompat.getColor(binding.root.context, org.jash.user.R.color.color_agreement)
                )
            } else {
                binding.categoryText.setTextColor(
                    ContextCompat.getColor(binding.root.context, android.R.color.darker_gray)
                )
                binding.categoryIcon.setColorFilter(
                    ContextCompat.getColor(binding.root.context, android.R.color.darker_gray)
                )
            }
            binding.root.setOnClickListener {
                onTypeClick(type)
            }
        }
    }

    class TypeDiffCallback : DiffUtil.ItemCallback<FtyTopeEntity>() {
        override fun areItemsTheSame(oldItem: FtyTopeEntity, newItem: FtyTopeEntity): Boolean {
            return oldItem.id == newItem.id
        }
        override fun areContentsTheSame(oldItem: FtyTopeEntity, newItem: FtyTopeEntity): Boolean {
            return oldItem == newItem
        }
    }
}
